package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.bean.BindPhoneInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;

/**
 * Created by young on 2016/6/15.
 * 绑定手机号验证码页面
 */
public class BindPhoneDetailActivity extends BaseActivity {

    private final int ERR_CODE_BIND_OTHER_PHONE = 60001;

    private final int ERR_CODE_BIND_SAME_PHONE = 8001;
    private final int ERR_CODE_RIGIST = 60003;//已注册
    private final int ERR_CODE_UNBIND = 60002;//未绑定手机号


    private final int MSG_ERR_CODE_BIND_OTHER_PHONE = 61001;

    private ViewGroup bind_phone_verity_container;
    private ViewGroup bind_phone_verity_linearcontainer;
    private TextView send_message_tips_and_phonenumber, err_tips_tv;
    private EditText input_veritycode_tv;
    private Button btn_send_sms, next_step_btn_vtcode;
    private String phonenumber;
    private final int MESSAGE_COUNTDOWN = 1;
    private final int JUMP_TO_MAIN = 3;
    private final int JUMP_TO_SETTING = 4;
    private final int TIPS_GONE = 2;
    private final int ERR_CODE_WRONG = 60001;
    private final int ERR_CODE_ERR = 80002;
    private int currentCount = EConstants.COUNT_COUNTDOWN;
    private int template;


    private Handler mhander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_COUNTDOWN:
                    //60秒倒计时
                    countdown();
                    break;
                case TIPS_GONE:
                    //错误提示
                    err_tips_tv.setVisibility(View.INVISIBLE);
                    break;
                case JUMP_TO_MAIN:
                    err_tips_tv.setVisibility(View.INVISIBLE);
                    //跳转到主页
                    EJumpManager.jumpToMain(0, BindPhoneDetailActivity.this);
                    finish();
                    break;
                case JUMP_TO_SETTING:
                    //跳转到设置页面
                    err_tips_tv.setVisibility(View.INVISIBLE);
                    //MeJumpManager.jumpToSetting2(BindPhoneDetailActivity.this,R.string.go_back);
                    finish();
                    break;
                case MSG_ERR_CODE_BIND_OTHER_PHONE:
                    //手机已绑定其他账号 错误提示
                    errTips(err_tips_tv, "验证码不正确，请重新输入!");
                    break;
                case ERR_CODE_ERR:
                    errTips(err_tips_tv, "验证码不正确，请重新输入!");
                    break;

                case ERR_CODE_BIND_OTHER_PHONE:
                    //手机已绑定其他账号 错误提示
                    errTips(err_tips_tv, "该手机号已绑定其他账号！");
                    break;
                case ERR_CODE_BIND_SAME_PHONE:
                    //更换手机时，输入的手机与已绑定手机号相同
                    errTips(err_tips_tv, "更换的手机号不能与已绑定的手机号相同!");
                    break;
                case ERR_CODE_RIGIST:
                    errTips(err_tips_tv, "该手机号已注册，请直接登录!");
                    break;
                case ERR_CODE_UNBIND:
                    errTips(err_tips_tv, "该手机号没有绑定账号!");
                    break;
            }
        }
    };


    private ViewOnClickListener mviewOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.next_step_btn_vtcode) {
                // next step
                String verityCode = input_veritycode_tv.getText().toString().trim();
                if (NetworkUtils.isOnline()) {
                    if (!MeUtil.isVerify_code_six(verityCode)) {
                        //如果不是6位纯数字验证码
                        errTips(err_tips_tv, "验证码不正确，请重新输入!");
                    } else {
                        if (!TextUtils.isEmpty(phonenumber)) {
                            //验证验证码是否正确
                            next(verityCode, phonenumber);
                        }
                    }
                } else {
                    errTips(err_tips_tv, getString(R.string.connect_disable));
                }

            }
            //重新获取验证码
            if (id == R.id.btn_send_sms) {
                if (!TextUtils.isEmpty(phonenumber) && template != 0) {
                    if (NetworkUtils.isOnline()) {
                        send_sms(phonenumber, template);
                    } else {
                        errTips(err_tips_tv, getString(R.string.connect_disable));
                    }

                }

            }
        }
    };


    @Override
    protected int setView() {
        return R.layout.activity_bindphone_verity;
    }

    @Override
    protected void findViews() {
        bind_phone_verity_container = (ViewGroup) findViewById(R.id.bind_phone_verity_container);
        bind_phone_verity_linearcontainer = (ViewGroup) findViewById(R.id.bind_phone_verity_linearcontainer);
        send_message_tips_and_phonenumber = (TextView) findViewById(R.id.send_message_tips_and_phonenumber);
        err_tips_tv = (TextView) findViewById(R.id.err_tips_tv);
        input_veritycode_tv = (EditText) findViewById(R.id.input_veritycode_tv);
        btn_send_sms = (Button) findViewById(R.id.btn_send_sms);
        next_step_btn_vtcode = (Button) findViewById(R.id.next_step_btn_vtcode);
    }

    @Override
    protected void initEvent() {
        //输入框校验
        input_veritycode_tv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                validbtn();
            }
        });
        input_veritycode_tv.setOnClickListener(mviewOnClickListener);
        btn_send_sms.setOnClickListener(mviewOnClickListener);
        next_step_btn_vtcode.setOnClickListener(mviewOnClickListener);


    }

    @Override
    protected void init() {
        setValideSource(true);
        setTitleText("验证码");
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                BindPhoneDetailActivity.this.finish();
            }
        });
    }

    @Override
    protected void loadData() {
        Intent intent = getIntent();

        if (intent != null) {
            phonenumber = intent.getStringExtra(IntentFlag.INTENT_FLAG_STR);
            template = intent.getIntExtra(IntentFlag.INTENT_FLAG_ID, 0);

//            send_sms(phonenumber, template);

            countdown();
        }

        if (!phonenumber.isEmpty()) {
            send_message_tips_and_phonenumber.setText(getResources().getString(R.string.send_message_tips) + phonenumber);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mhander.removeCallbacksAndMessages(null);
    }

    /**
     * 验证验证码输入状态
     */
    private void validbtn() {
        String vertycode = input_veritycode_tv.getText().toString();
        if (TextUtils.isEmpty(vertycode)) {
            next_step_btn_vtcode.setEnabled(false);
        } else {
            next_step_btn_vtcode.setEnabled(true);
        }
    }

    /**
     * 验证验证码是否正确
     *
     * @param verityCode
     * @param phonenumber
     */

    private void next(final String verityCode, final String phonenumber) {
        MeDao.getInstance().ValidSmsVerityCode(EApplication.BRAND_ID + "", phonenumber, verityCode,
                new BaseExtCallBack(BindPhoneDetailActivity.this) {


                    @Override
                    public void failed(int errorCode, Object data) {
                        if (errorCode == ERR_CODE_WRONG) {
                            mhander.sendEmptyMessage(ERR_CODE_WRONG);
                        } else if (errorCode == ERR_CODE_ERR) {
                            mhander.sendEmptyMessage(ERR_CODE_ERR);
                        } else {
                            errTips(err_tips_tv, String.valueOf(data));
                        }
                    }

                    @Override
                    public void failed(Object data) {
                        if (data instanceof NoConnectionError) {
                            errTips(err_tips_tv, getString(R.string.connect_disable));

                        } else if (data instanceof TimeoutError) {
                            errTips(err_tips_tv, getString(R.string.connect_timeout));

                        } else {
                            errTips(err_tips_tv, getString(R.string.unknown_error));
                        }
                    }

                    @Override
                    public void success(Object data) {
                        Boolean b = (Boolean) data;
                        if (b) {
                            //根据不同来源做相应的处理
                            switch (template) {
                                //绑定手机号
                                case EConstants.Template.TEMPLATE_ONE:
                                    BindPhone(verityCode, phonenumber);
                                    break;
                                //注册
                                case EConstants.Template.TEMPLATE_TWO:
                                    EJumpManager.jumpToRegister(R.string.login, BindPhoneDetailActivity.this, verityCode, phonenumber);

                                    break;
                                //忘记密码
                                case EConstants.Template.TEMPLATE_THREE:
                                    MeJumpManager.jumpResetPasswordActivity(BindPhoneDetailActivity.this, R.string.go_back, phonenumber, verityCode);
                                    break;
                                case EConstants.Template.TEMPLATE_FOUR:
                                    BindPhone(verityCode, phonenumber);

                                    break;
                            }
                        }
                    }
                });
    }

    /**
     * 输入验证码下一步
     * 绑定手机号
     */
    private void BindPhone(String verityCode, String phonenumber) {
        if (NetworkUtils.isOnline()) {
            MeDao.getInstance().BindPhone(CWSys.getSharedLong(EConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "", EApplication.BRAND_ID + "", phonenumber, verityCode,
                    new BaseExtCallBack(BindPhoneDetailActivity.this) {


                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            if (errorCode != 17) {
                                errTips(err_tips_tv, String.valueOf(data));
                            }

                        }

                        @Override
                        public void failed(Object data) {
                            if (data instanceof NoConnectionError) {
                                errTips(err_tips_tv, getString(R.string.connect_disable));

                            } else if (data instanceof TimeoutError) {
                                errTips(err_tips_tv, getString(R.string.connect_timeout));

                            } else {
                                errTips(err_tips_tv, getString(R.string.unknown_error));
                            }
                        }

                        @Override
                        public void success(Object data) {
                            BindPhoneInfo bindPhoneInfo = (BindPhoneInfo) data;
                            bindPhoneInfo.setMobile(AESCBCUtil.decrypt(bindPhoneInfo.getMobile(), AESCBCUtil.AESCBC_HEX));
                            try {
                                CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), bindPhoneInfo.getMobile());
                                CWSys.setSerializableObject(EConstants.SHARE_PRE_CURR_BIND_PHONE_INFO, bindPhoneInfo);
                            } catch (Exception e) {
                                e.getStackTrace();
                            }
                            if (template == EConstants.Template.TEMPLATE_FOUR) {
                                errTips(err_tips_tv, "更换手机号成功！");
                                mhander.sendEmptyMessageDelayed(JUMP_TO_SETTING, 1000);
                            } else if (template == EConstants.Template.TEMPLATE_ONE) {
                                errTips(err_tips_tv, "绑定手机号成功！");
                                mhander.sendEmptyMessageDelayed(JUMP_TO_MAIN, 1000);
                            }
                        }
                    });
        } else {
            errTips(err_tips_tv, getString(R.string.request_failed));
        }
    }

    /**
     * 获取手机验证码
     */
    private void send_sms(String phonenumber, int template) {
        MeDao.getInstance().getSmsVerityCode(EApplication.BRAND_ID + "", phonenumber, "", "", template + "",
                new BaseCallBack() {

                    @Override
                    public void success(Object data) {
                        Log.d("retryscore", "############success###########");
                    }

                    @Override
                    public void failed(int errorCode, Object data) {

                        if (errorCode == ERR_CODE_BIND_OTHER_PHONE) {
                            mhander.sendEmptyMessage(MSG_ERR_CODE_BIND_OTHER_PHONE);
                        } else if (errorCode == ERR_CODE_BIND_SAME_PHONE) {
                            mhander.sendEmptyMessage(ERR_CODE_BIND_SAME_PHONE);
                        } else if (errorCode == ERR_CODE_RIGIST) {
                            mhander.sendEmptyMessage(ERR_CODE_RIGIST);
                        } else if (errorCode == ERR_CODE_UNBIND) {
                            mhander.sendEmptyMessage(ERR_CODE_UNBIND);
                        } else {
                            errTips(err_tips_tv, String.valueOf(data));
                        }

                    }

                    @Override
                    public void failed(Object data) {

                        if (data instanceof NoConnectionError) {
                            errTips(err_tips_tv, getString(R.string.connect_disable));
                        } else if (data instanceof TimeoutError) {
                            errTips(err_tips_tv, getString(R.string.connect_timeout));
                        } else if (data instanceof ServerError) {
                            errTips(err_tips_tv, getString(R.string.connect_server_error));
                        } else {
                            errTips(err_tips_tv, getString(R.string.unknown_error));
                        }

                    }
                }


        );
        mhander.sendEmptyMessage(MESSAGE_COUNTDOWN);
    }

    /**
     * 控制软键盘布局
     *
     * @param root         最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect rect = new Rect();
                        // 获取root在窗体的可视区域
                        root.getWindowVisibleDisplayFrame(rect);
                        // 获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                        int rootInvisibleHeight = root.getRootView().getHeight()
                                - rect.bottom;
                        // 若不可视区域高度大于100，则键盘显示
                        if (rootInvisibleHeight > 100) {
                            int[] location = new int[2];
                            // 获取scrollToView在窗体的坐标
                            scrollToView.getLocationInWindow(location);
                            // 计算root滚动高度，使scrollToView在可见区域
                            int srollHeight = (location[1]
                                    + scrollToView.getHeight()) - rect.bottom;
                            root.scrollTo(0, srollHeight);
                        } else {
                            // 键盘隐藏
                            root.scrollTo(0, 0);
                        }
                    }
                });
    }

    /**
     * 下发短信按钮倒计时60秒
     */
    private void countdown() {
        if (currentCount > 0) {
            btn_send_sms.setText(currentCount + getResources().getString(R.string.send_message_tips_right));
            btn_send_sms.setEnabled(false);
            mhander.removeMessages(MESSAGE_COUNTDOWN);
            mhander.sendEmptyMessageDelayed(MESSAGE_COUNTDOWN, 1000);
            currentCount -= 1;
        } else {
            currentCount = EConstants.COUNT_COUNTDOWN;
            btn_send_sms.setText(getResources().getString(R.string.resend_message_again));
            btn_send_sms.setEnabled(true);

        }

    }

    /**
     * 错误提示动画
     *
     * @param view
     */
    private void errTips(final View view, String tips) {
        err_tips_tv.setText(tips);
        err_tips_tv.setVisibility(View.VISIBLE);
        mhander.sendEmptyMessageDelayed(TIPS_GONE, 3000);
    }


}
